/**
 * @param {string} watermarkText 水印文本
 * @returns {HTMLDivElement} 水印 DOM 元素
 */
function createWatermark(watermarkText) {
  const can = document.createElement('canvas');
  const ctx = can.getContext('2d');
  can.width = 400;
  can.height = 250;
 
  // 保存上下文状态
  ctx.save();
  
  ctx.font = '16px Microsoft YaHei';
  ctx.fillStyle = 'rgba(72, 160, 219, 0.1)';
  ctx.textAlign = 'left';
  ctx.textBaseline = 'middle';
  
  // 移动到中心点再旋转
  ctx.translate(can.width / 2, can.height / 2);
  ctx.rotate(-20 * Math.PI / 180);
  
  // 获取当前日期
  const currentDate = new Date();
  const year = currentDate.getFullYear();
  const month = String(currentDate.getMonth() + 1).padStart(2, '0');
  const day = String(currentDate.getDate()).padStart(2, '0');
  const currentDateString = `${year}-${month}-${day}`;
  ctx.fillText(`${watermarkText} ${currentDateString}`, -can.width / 2 + 40, 0);
  
  // 恢复上下文状态
  ctx.restore();
 
  const div = document.createElement('div');
  div.style.pointerEvents = 'none';
  div.style.top = '0px';
  div.style.left = '0px';
  div.style.position = 'fixed';
  div.style.zIndex = '9999';  // 降低 z-index，避免遮挡内容
  div.style.width = '100%';
  div.style.height = '100%';
  div.style.background = `url(${can.toDataURL('image/png')}) repeat`;
  div.style.backgroundSize = '400px 250px';
  return div;
}
 
// 自定义水印指令
export default {
  mounted(el, binding) {
    const { watermarkText } = binding.value || {};
    
    console.log('水印指令 mounted，watermarkText:', watermarkText);
    
    if (!watermarkText) {
      console.warn('水印文本为空，等待更新');
      // 即使为空也创建一个延迟检查
      el.__watermarkCheckTimer = setTimeout(() => {
        const newText = binding.value?.watermarkText;
        if (newText) {
          const watermarkDiv = createWatermark(newText);
          el.__watermark__ = watermarkDiv;
          document.body.appendChild(watermarkDiv);
        }
      }, 100);
      return;
    }

    const watermarkDiv = createWatermark(watermarkText);
    el.__watermark__ = watermarkDiv;
    document.body.appendChild(watermarkDiv);
    console.log('水印已创建并添加到页面');
  },
  unmounted(el) {
    if (el.__watermarkCheckTimer) {
      clearTimeout(el.__watermarkCheckTimer);
      delete el.__watermarkCheckTimer;
    }
    if (el.__watermark__ && el.__watermark__.parentNode) {
      document.body.removeChild(el.__watermark__);
      delete el.__watermark__;
      console.log('水印已移除');
    }
  },
  updated(el, binding) {
    // 如果水印文本变化，更新水印
    const { watermarkText } = binding.value || {};
    console.log('水印指令 updated，watermarkText:', watermarkText);
    
    if (watermarkText) {
      // 移除旧水印
      if (el.__watermark__ && el.__watermark__.parentNode) {
        document.body.removeChild(el.__watermark__);
      }
      // 创建新水印
      const watermarkDiv = createWatermark(watermarkText);
      el.__watermark__ = watermarkDiv;
      document.body.appendChild(watermarkDiv);
      console.log('水印已更新');
    }
  }
};